package opensource.xml.jdom;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

/**
 * @author Guoxuepin(guoxp@bingosoft.net) 2009-3-4 上午11:42:25 ChangeLog:
 *         ReadMe:JDOM 读取XML配置文件的例子
 */
public class StrutsConfig {

	private static StrutsConfig instance = new StrutsConfig();
	private static final String CONFIG_FILE_NAME = "test-jdom.xml";
	private Element rootElement = null;
	StrutsBean strutsBean = new StrutsBean();
	Map<String, String> beanMap = new HashMap<String, String>();

	public StrutsConfig() {
		SAXBuilder sb = new SAXBuilder();
		try {
			Document doc = sb.build(CONFIG_FILE_NAME);//参数与文件的文件全路径名
			this.rootElement = doc.getRootElement();

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		initStrutsConfig();
		initBeans();

	}

	private void initStrutsConfig() {
		try {
			Element formBeanNode = (Element) XPath
					.selectSingleNode(rootElement, "//struts-config/form-beans/form-bean");
			strutsBean.setFormBean(formBeanNode.getText());
			// 显示一个节点中的内容
			System.out.println("form-bean " + strutsBean.getFormBean());
			System.out.println("form-bean name=" + formBeanNode.getAttributeValue("name"));
			System.out.println("form-bean type=" + formBeanNode.getAttributeValue("type"));

		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private void initBeans() {
		try {
			List<Element> beansList = (List) XPath.selectNodes(rootElement, "//struts-config/plug-in");
			for (Element bean : beansList) {
				String id = bean.getAttributeValue("id");
				String className = bean.getAttributeValue("className");
				beanMap.put(id, className);
				// 显示多个plug－in中的内容
				//System.out.println("plug-in:id=" + id + "\tclassName=" + beanMap.get(id));
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}

	public static StrutsConfig getInstance() {
		return instance;
	}

	public static void main(String[] args) {
	}

}
